package com.qupai.lib_base.widget.sticker

import android.graphics.*
import android.view.MotionEvent
import com.qupai.lib_base.widget.sticker.utils.PointUtils.getBitmapPoints
import kotlin.math.atan2
import kotlin.math.sqrt

class Sticker internal constructor(  // 原图片
    val srcImage: Bitmap?
) {
    // 绘制图片的矩阵
    val matrix: Matrix = Matrix()

    /**
     * 绘制图片
     *
     * @param canvas
     */
    fun draw(canvas: Canvas) {
        canvas.drawBitmap(srcImage!!, matrix, null)
    }

    /**
     * 获取手势中心点
     *
     * @param event
     */
    fun getMidPoint(event: MotionEvent): PointF {
        val point = PointF()
        val x = event.getX(0) + event.getX(1)
        val y = event.getY(0) + event.getY(1)
        point[x / 2] = y / 2
        return point
    }

    /**
     * 获取图片中心点
     */
    fun getImageMidPoint(matrix: Matrix?): PointF {
        val point = PointF()
        val points = getBitmapPoints(srcImage!!, matrix!!)
        val x1 = points[0]
        val x2 = points[2]
        val y2 = points[3]
        val y4 = points[7]
        point[(x1 + x2) / 2] = (y2 + y4) / 2
        return point
    }

    /**
     * 获取手指的旋转角度
     *
     * @param event
     * @return
     */
    fun getSpaceRotation(event: MotionEvent, imageMidPoint: PointF): Float {
        val deltaX = (event.getX(0) - imageMidPoint.x).toDouble()
        val deltaY = (event.getY(0) - imageMidPoint.y).toDouble()
        val radians = atan2(deltaY, deltaX)
        return Math.toDegrees(radians).toFloat()
    }

    /**
     * 【多点缩放】获取手指间的距离
     *
     * @param event
     * @return
     */
    fun getMultiTouchDistance(event: MotionEvent): Float {
        val x = event.getX(0) - event.getX(1)
        val y = event.getY(0) - event.getY(1)
        return sqrt((x * x + y * y).toDouble()).toFloat()
    }

    /**
     * 【单点缩放】获取手指和图片中心点的距离
     *
     * @param event
     * @return
     */
    fun getSingleTouchDistance(event: MotionEvent, imageMidPoint: PointF): Float {
        val x = event.getX(0) - imageMidPoint.x
        val y = event.getY(0) - imageMidPoint.y
        return sqrt((x * x + y * y).toDouble()).toFloat()
    }

    val srcImageBound: RectF
        get() {
            val dst = RectF()
            matrix.mapRect(dst, RectF(0f, 0f, stickerWidth.toFloat(), stickerHeight.toFloat()))
            return dst
        }
    val stickerWidth: Int
        get() = srcImage?.width ?: 0
    val stickerHeight: Int
        get() = srcImage?.height ?: 0
}